import requests
import json


ding_app_key = "dingmzmum9bp6f2g8rwo"
ding_app_secret = "t0ckYuVmvTON3ye2ig8Cf5VLyxo6c96ULbZ7FO_-Aozcy4UNiFlzaUNSZ7OSVSEb"
ding_agent_id="dinge5g2lsewja5r2vpx"

def get_access_token():
    """获取钉钉访问令牌"""
    url = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
    try:
        response = requests.post(
            url,
            json={"appKey": ding_app_key, "appSecret": ding_app_secret}
        )
        if response.status_code == 200:
            return response.json().get("accessToken")
        return None
    except Exception:
        return None


def get_user_id(mobile, access_token):
    """根据手机号获取用户ID"""
    url = f"https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token={access_token}"
    headers = {
        "x-acs-dingtalk-access-token": access_token,
        "Content-Type": "application/json"
    }
    try:
        response = requests.post(url,headers=headers,json={"mobile": mobile})
        if response.status_code == 200:
            result = response.json().get("result")
            return result.get("userid") if result else None
        return None
    except Exception:
        return None


def send_dingtalk_message(mobile, content,title="系统通知",agent_id = ding_agent_id):
    # 获取访问令牌
    access_token = get_access_token()
    if not access_token:
        return False, "获取access_token失败"
    # 查询用户ID
    user_id = get_user_id(mobile, access_token)
    if not user_id:
        return False, "未找到对应用户"
    # 构造消息体
    message = {
        "robotCode": agent_id,
        "userIds": [user_id],
        "msgKey":"sampleText",
        "msgParam": json.dumps({"content":content}),
    }
    # 发送请求
    url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"
    headers = {
        "x-acs-dingtalk-access-token": access_token,
        "Content-Type": "application/json"
    }
    try:
        response = requests.post(url, headers=headers, json=message)
        print(response.json())
        if response.status_code == 200:
            return True, response.json()
        return False, f"请求失败，状态码：{response.status_code}"
    except Exception as e:
        return False, f"请求异常：{str(e)}"


# 使用示例
if __name__ == "__main__":
    # 发送消息
    result = send_dingtalk_message(
        mobile="13302459352",
        content="### test!!!用户取消订单通知\n\n**订单号**: 202309200001\n\n**店铺**: Forio\n\n**SKU**: GG-xx-xxx-test\n\n",
        title="取消订单"
    )
    print("发送成功" if result[0] else "发送失败")
    print("详细信息:", result[1])